package com.jerry.spring.security.jwt.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jerry.spring.security.jwt.domain.LoginUser;
import com.jerry.spring.security.jwt.domain.entity.User;
import com.jerry.spring.security.jwt.mapper.MenuMapper;
import com.jerry.spring.security.jwt.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户服务
 *
 * @author jerry 2024/5/8 20:36
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名从数据库查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);

        // 如果查询不到数据，则抛出异常
        if (ObjectUtil.isNull(user)) {
            log.info("{} 用户不存在", username);
            throw new UsernameNotFoundException("用户不存在");
        }

        // 查询用户权限信息
        List<String> permissions = menuMapper.selectPermsByUserId(user.getId());

        // 最终封装成UserDetails返回
        return new LoginUser(user, permissions);
    }
}
